angular.module('inspinia').controller('agentActivityDetailSaveCtrl',function($scope,$http,i18nService,SweetAlert,$document,$state,$stateParams){
    i18nService.setCurrentLang('zh-cn');  //设置语言为中文
    $scope.paginationOptions=angular.copy($scope.paginationOptions);

    $scope.isDetail=$stateParams.isDetail=="1" || $stateParams.isDetail=="3";

    $scope.actTypeSelect = [{text:"全部",value:""},{text:"百团大战榜",value:"1"},{text:"千团大战",value:"2"}];
    $scope.actTypeStr=angular.toJson($scope.actTypeSelect);

    $scope.agentSelect = [{text:"全部",value:"1"},{text:"直属",value:"2"}];

    //奖品类型
    $scope.rewardTypeSelect = [{text:"全部",value:""},{text:"现金",value:"1"},{text:"实物",value:"2"},{text:"优惠券",value:"3"}];
    $scope.rewardTypeStr=angular.toJson($scope.rewardTypeSelect);

    //计算方式
    $scope.calcTypeSelect = [{text:"固定金额",value:"1"},{text:"浮动金额",value:"2"}];
    $scope.calcTypeSelect1 = [{text:"固定金额",value:"1"},{text:"浮动金额",value:"2"}];

    $scope.addInfo={actType:"1"};

    $scope.getActStr=function(item){
        if(item.rewardType=="1"){
            if(item.calcType=="1"){//固定
                item.actStr=item.rewardNum+"元";
            }else if(item.calcType=="2"){//公式
                item.actStr="悬赏金"+item.rewardNum+"元X参与率";
            }
        }
    }

    $scope.initData=function(actDetCode){
        $http.post("agentActivityAction/getAgentActivityDetail", "actDetCode="+actDetCode,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function(data){
                if(data.status){
                    $scope.addInfo=data.info;
                    if($scope.addInfo.actType=="1"){
                        $scope.calcTypeSelect1 = [{text:"固定金额",value:"1"}];
                        if($scope.addInfo.activeExtMap==null){
                            $scope.addInfo.activeExtMap={subMerchant:"2",merchantNum:"",aatTop:"",subMerchantActivity:"2",subMerchantTrans:"2",coefficient1:"",coefficient2:""};
                        }
                    }else{
                        $scope.calcTypeSelect1 = [{text:"固定金额",value:"1"},{text:"浮动金额",value:"2"}];
                        if($scope.addInfo.activeExtMap==null){
                            $scope.addInfo.activeExtMap={aatTop:"",subPrideMerchant:"1",coefficient:"",subMerchantActivity:"1",subMerchantTrans:"1"};
                        }
                    }
                    //奖品
                    if($scope.addInfo.rewardList!=null&&$scope.addInfo.rewardList.length>0){
                        for(var i=0;i<$scope.addInfo.rewardList.length;i++){
                            var item=$scope.addInfo.rewardList[i];
                            //转换显示
                            $scope.getActStr(item);
                        }

                    }else{
                        $scope.addInfo.rewardList=[];
                    }

                    $scope.result=$scope.addInfo.rewardList;
                }
            });
    }
    $scope.initData($stateParams.actDetCode);

    $scope.userGrid={                           //配置表格
        data: 'result',
        paginationPageSize:10,                  //分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs:[                           //表格数据
            { field: 'rankSeq',displayName:'领取名次',width:180},
            { field: 'rewardCode',displayName:'奖项编号',width:180},
            { field: 'rewardType',displayName:'奖项类型',width:180,cellFilter:"formatDropping:" +  $scope.rewardTypeStr },
            { field: 'rewardName',displayName:'奖项名称',width:180},
            { field: 'actStr',displayName:'奖励金额',width:240},
            { field: 'id',displayName:'操作',width:180,cellTemplate:
                    '<div class="lh30">'+
                        '<a target="_blank" ng-show="!grid.appScope.isDetail" ng-click="grid.appScope.modalShowEdit(row.entity)">修改 </a> ' +
                        '<a target="_blank" ng-show="!grid.appScope.isDetail" ng-click="grid.appScope.deleteReward(row,rowRenderIndex)"> | 删除</a> ' +
                    '</div>'
            }
        ],
        onRegisterApi: function(gridApi) {
            $scope.userGridApi = gridApi;
        }
    };

    //新增奖项
    $scope.modalShow = function(){
        $scope.title="新增奖项";
        $scope.idEdit=false;
        $scope.rewardInfo={rewardType:""};
        $('#appModal').modal('show');
    };

    $scope.modalcancel = function(){
        $('#appModal').modal('hide');
    };
    $scope.modalShowEdit = function(entity){
        $scope.rewardInfo=angular.copy(entity);
        $scope.rewardInfo.rankSeqStart= $scope.rewardInfo.rankSeq;
        $scope.rewardInfo.rankSeqEnd= $scope.rewardInfo.rankSeq;
        $scope.oldRankSeq=Number($scope.rewardInfo.rankSeq);//记录原值
        $scope.idEdit=true;
        $scope.title="修改奖项";
        $('#appModal').modal('show');
    };

    $scope.rewardTypeChange=function(){
        if($scope.rewardInfo.rewardType=="1"){
            $scope.rewardInfo.calcType="1";
            $scope.rewardInfo.rewardNum=null;
        }else{
            //物品，券数量默认1
            $scope.rewardInfo.calcType=null;
            $scope.rewardInfo.rewardNum=1;
        }
    }
    $scope.calcTypeChange=function(){
        $scope.rewardInfo.rewardNum=null;
    }

    function checkNum(obj,reg){
        if(obj==undefined || obj==null || obj===""){
            return true;
        }else{
            if(!reg.test(obj)){
                return true;
            }
        }
        return false;
    }

    $scope.saveRewardInfo=function(){
        if(checkNum($scope.rewardInfo.rankSeqStart,/^[1-9][0-9]*$/) ||checkNum($scope.rewardInfo.rankSeqEnd,/^[1-9][0-9]*$/)){
            $scope.notice("领取名次值不正确!");
            return;
        }
        //校验名称是否已存在
        if(Number($scope.rewardInfo.rankSeqStart)>Number($scope.rewardInfo.rankSeqStart)){
            $scope.notice("领取名次值起始值不能小于结束值!");
            return;
        }
        if($scope.rewardInfo.rewardType=="1"){
            if(checkNum($scope.rewardInfo.rewardNum,/^([1-9]\d{0,9}|0)(\.\d{1,2})?$/)){
                $scope.notice("奖励金额值不正确!");
                return;
            }
        }
        var start=Number($scope.rewardInfo.rankSeqStart);
        var end;
        if($scope.idEdit){
            end=start;
        }else{
            end=Number($scope.rewardInfo.rankSeqEnd);
        }
        if($scope.addInfo.rewardList!=null&&$scope.addInfo.rewardList.length>0){
            if(start==end){
                for(var i=0;i<$scope.addInfo.rewardList.length;i++){
                    var item=$scope.addInfo.rewardList[i];
                    var now=Number(item.rankSeq);
                    if(now==start){
                        if($scope.idEdit){//编辑 排除自己
                            if(start!=$scope.oldRankSeq){
                                $scope.notice("该领取名次已有名次存在!");
                                return;
                            }
                        }else{
                            $scope.notice("该领取名次已有名次存在!");
                            return;
                        }
                    }
                }
            }else{
                for(var i=0;i<$scope.addInfo.rewardList.length;i++){
                    var item=$scope.addInfo.rewardList[i];
                    var now=Number(item.rankSeq);
                    if(now>=start&&now<=end){
                        $scope.notice("该领取名次已有名次存在!");
                        return;
                    }
                }
            }
        }
        if($scope.idEdit){
            for(var i=0;i<$scope.addInfo.rewardList.length;i++){
                var item=$scope.addInfo.rewardList[i];
                var now=Number(item.rankSeq);
                if($scope.oldRankSeq==now){
                    item.rankSeq=$scope.rewardInfo.rankSeqStart;
                    item.rewardType=$scope.rewardInfo.rewardType;
                    item.rewardName=$scope.rewardInfo.rewardName;
                    item.rewardNum=$scope.rewardInfo.rewardNum;
                    item.calcType=$scope.rewardInfo.calcType;
                    //转换显示
                    $scope.getActStr(item);
                }

            }
        }else{
            for(var j=start;j<=end;j++){
                var item={rankSeq:j,rewardCode:null,rewardType:$scope.rewardInfo.rewardType,rewardName:$scope.rewardInfo.rewardName,
                    rewardNum:$scope.rewardInfo.rewardNum,calcType:$scope.rewardInfo.calcType,actStr:null};
                //转换显示
                $scope.getActStr(item);
                $scope.addInfo.rewardList.push(item);
            }
        }

        //排序
        $scope.addInfo.rewardList.sort(function(a, b){
            var x = Number(a.rankSeq);
            var y = Number(b.rankSeq);
            if (x < y) {
                return -1;
            }
            if (x > y) {
                return 1;
            }
            return 0;
        });
        $scope.modalcancel();
    }
    //单个删除
    $scope.deleteReward=function(entity,index){
        SweetAlert.swal({
                title: "确定删除吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    $scope.addInfo.rewardList.splice(index, 1);
                }
            });
    }
    //批量删除
    $scope.deleteRewardBatch=function(){
        var selectList = $scope.userGridApi.selection.getSelectedRows();
        if(selectList!=null&&selectList.length<=0){
            $scope.notice("请选择需要删除得数据!");
            return;
        }
        var title="选择"+selectList.length+"条数据,确定删除吗？"
        SweetAlert.swal({
                title: title,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    for(var i=0;i<=selectList.length;i++){
                        var item1=selectList[i];
                        for(var j=0;j<$scope.addInfo.rewardList.length;j++){
                            var item2=$scope.addInfo.rewardList[j];
                            if(item1.rankSeq==item2.rankSeq){
                                $scope.addInfo.rewardList.splice(j, 1);
                                break;
                            }
                        }
                    }
                }
            });
    }


    $scope.submitting=false;
    $scope.saveInfo=function(){
        if($scope.addInfo.actType=="1"){
            if(checkNum($scope.addInfo.activeExtMap.merchantNum,/^[1-9][0-9]*$/)
                ||checkNum($scope.addInfo.activeExtMap.aatTop,/^[1-9][0-9]*$/)
            ){
                $scope.notice("榜单规则设置数据错误!");
                return;
            }
            if(checkNum($scope.addInfo.activeExtMap.coefficient1,/^([1-9]\d{0,9}|0)(\.\d{1,3})?$/)
                ||checkNum($scope.addInfo.activeExtMap.coefficient2,/^([1-9]\d{0,9}|0)(\.\d{1,3})?$/)
            ){
                $scope.notice("牛气值公式数据错误!");
                return;
            }
            if(Number($scope.addInfo.activeExtMap.aatTop)>1000){
                $scope.notice("最高可输入1000名!");
                return;
            }
        }else{
            if(checkNum($scope.addInfo.activeExtMap.aatTop,/^[1-9][0-9]*$/)){
                $scope.notice("榜单规则设置数据错误!");
                return;
            }
            if(checkNum($scope.addInfo.activeExtMap.coefficient,/^([1-9]\d{0,9}|0)(\.\d{1,3})?$/)){
                $scope.notice("壕气值公式数据错误!");
                return;
            }
            if(Number($scope.addInfo.activeExtMap.aatTop)>1000){
                $scope.notice("最高可输入1000名!");
                return;
            }
        }

        if ($scope.submitting) {
            return;
        }
        $scope.submitting = true;
        var data = {
            info:angular.toJson($scope.addInfo)
        };
        $http.post("agentActivityAction/editAgentActivityDetail",data,$scope.postCfgAllCurrency)
            .success(function (data) {
                $scope.notice(data.msg);
                if (data.status) {
                    $scope.toBack();
                }
                $scope.submitting = false;
            }).error(function(data){
                $scope.notice(data.msg);
                $scope.submitting = false;
            });
    };

    $scope.toBack=function(){
        if($stateParams.isDetail==3){
            $state.transitionTo('agent.agentActivitySave',{actCode:$stateParams.actCode,isDetail:2},{reload:true});
        }else{
            $state.transitionTo('agent.agentActivitySave',{actCode:$stateParams.actCode,isDetail:$stateParams.isDetail},{reload:true});
        }
    }
});